import React, { useState, useEffect } from "react";
import { Modal, Form, Input, Button, Upload, Avatar, message, Image } from "antd";
import { UserOutlined, UploadOutlined } from "@ant-design/icons";
import { useSelector, useDispatch } from "react-redux";
import { setProfile, clearToken, clearProfile } from "@/store/modules/userStore";
import { uploadApi } from "@/apis/upload";
import { updateUserInfoApi, CheckOldPassword } from "@/apis/user";
import isEqual from "lodash/isEqual";
import router from "@/router";

const UserProfileModal: React.FC<{ open: boolean; onClose: () => void }> = ({ open, onClose }) => {
  const dispatch = useDispatch();
  const profile = useSelector((state: any) => state.user.profile);
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState(profile?.avatar || "");
  const [uploading, setUploading] = useState(false);
  const [oldPasswordModalOpen, setOldPasswordModalOpen] = useState(false);
  const [oldPassword, setOldPassword] = useState("");
  const [oldPasswordLoading, setOldPasswordLoading] = useState(false);
  const [pendingValues, setPendingValues] = useState<any>(null);
  const [isChanged, setIsChanged] = useState(false);

  // 头像上传
  const handleUpload = async (info: any) => {
    setUploading(true);
    try {
      const res: any = await uploadApi(info.file);
      if (res.code === 0) {
        setAvatarUrl(res.data);
        form.setFieldsValue({ avatar: res.data });
        setIsChanged(true);
        message.success("头像上传成功");
      } else {
        message.error("头像上传失败");
      }
    } catch {
      message.error("头像上传失败");
    } finally {
      setUploading(false);
    }
  };

  // 提交表单
  const onFinish = async (values: any) => {
    try {
      const res: any = await updateUserInfoApi({ ...profile, ...values, avatar: avatarUrl });
      if (res.code === 0) {
        dispatch(setProfile(res.data));
        // 判断是否只修改了头像
        const onlyAvatarChanged =
          values.username === profile.username &&
          values.email === profile.email &&
          !values.password;
        if (onlyAvatarChanged) {
          message.success("头像更新成功");
          onClose();
        } else {
          message.success("信息更新成功，请重新登录");
          onClose();
          setTimeout(() => {
            dispatch(clearToken());
            dispatch(clearProfile());
            router.navigate("/login");
          }, 1000);
        }
      } else {
        message.error(res.message || "更新失败");
      }
    } catch {
      message.error("请求失败");
    }
  };

  // 提交表单前，弹出旧密码输入框
  const handleOk = async () => {
    // 判断是否有改动
    if (!isChanged) return;
    // 先校验表单
    try {
      const values = await form.validateFields();
      setPendingValues(values);
      setOldPasswordModalOpen(true);
    } catch {
      // 校验失败
    }
  };

  // 旧密码校验并最终提交
  const handleOldPasswordOk = async () => {
    setOldPasswordLoading(true);
    try {
      const res: any = await CheckOldPassword({ oldPassword: oldPassword });
      if (res.code === 0) {
        // 校验通过，提交表单
        setOldPasswordModalOpen(false);
        setOldPassword("");
        await onFinish(pendingValues);
      } else {
        message.error(res.message || "旧密码错误");
      }
    } catch {
      message.error("旧密码校验失败");
    } finally {
      setOldPasswordLoading(false);
    }
  };

  // 监听初始值变化，重置表单和 isChanged
  useEffect(() => {
    form.setFieldsValue({ ...profile, avatar: profile?.avatar || "", password: "" });
    setAvatarUrl(profile?.avatar || "");
    setIsChanged(false);
  }, [profile, open, form]);

  // 判断是否有改动
  const handleValuesChange = (changed: any, all: any) => {
    const initial = { ...profile, avatar: avatarUrl };
    setIsChanged(!isEqual(initial, all));
  };

  return (
    <>
      <Modal
        title="个人信息设置"
        open={open}
        onCancel={onClose}
        onOk={handleOk}
        destroyOnClose
        okButtonProps={{ disabled: !isChanged }}
        centered
      >
        <Form
          form={form}
          initialValues={{ ...profile, avatar: avatarUrl }}
          onFinish={onFinish}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 18 }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item label="头像" name="avatar">
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
              <Avatar
                size={96}
                src={avatarUrl}
                icon={<UserOutlined />}
                style={{ cursor: "pointer", marginBottom: 16 }}
              />
              <Upload
                showUploadList={false}
                customRequest={handleUpload}
                accept="image/*"
              >
                <Button loading={uploading} icon={<UploadOutlined />} style={{ display: "block", margin: "0 auto" }}>
                  更换头像
                </Button>
              </Upload>
            </div>
          </Form.Item>
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "邮箱格式不正确" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              { min: 6, message: "密码至少6位" },
            ]}
          >
            <Input.Password placeholder="如需修改请填写新密码" />
          </Form.Item>
          {/* 你可以根据需要添加更多字段 */}
        </Form>
      </Modal>
      <Modal
        title="请输入旧密码验证"
        open={oldPasswordModalOpen}
        onCancel={() => { setOldPasswordModalOpen(false); setOldPassword(""); }}
        onOk={handleOldPasswordOk}
        confirmLoading={oldPasswordLoading}
        okText="确认"
        cancelText="取消"
        centered
      >
        <Input.Password
          placeholder="请输入旧密码"
          value={oldPassword}
          onChange={e => setOldPassword(e.target.value)}
          onPressEnter={handleOldPasswordOk}
        />
      </Modal>
    </>
  );
};

export default UserProfileModal;